#!/bin/bash

# https://github.com/inconshreveable/ngrok.git



function gen_cert() {

	if [ "$DOMAIN" == "" ]; then
		echo " WARN : plesae specify your root domain (my.domain.com)";
		exit 1
	fi
	
	$STELLA_API del_folder $CERT_HOME
	mkdir -p $CERT_HOME
	cd $CERT_HOME

	openssl genrsa -out rootCA.key 2048
	openssl req -x509 -new -nodes -key rootCA.key -subj "/CN=$DOMAIN" -days 5000 -out rootCA.pem
	openssl genrsa -out device.key 2048
	openssl req -new -key device.key -subj "/CN=$DOMAIN" -out device.csr
	openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 5000

	cp -f rootCA.pem $NGROK_HOME/assets/client/tls/ngrokroot.crt
}

function gen_cert2() {
    MY_FILES=$1
    DOMAIN=$2
    echo "MY_FILES=${MY_FILES}"
    echo "DOMAIN=${DOMAIN}"
    if [ "$MY_FILES" == "" ]; then
		echo " WARN : plesae specify path to gen cert2";
		exit 1
	fi
    if [ "$DOMAIN" == "" ]; then
		echo " WARN : plesae specify your root domain (my.domain.com)";
		exit 1
	fi
    cd ${MY_FILES}
    if [ ! -f "${MY_FILES}/base.pem" ]; then
        openssl genrsa -out base.key 2048
        openssl req -new -x509 -nodes -key base.key -days 10000 -subj "/CN=${DOMAIN}" -out base.pem
        openssl genrsa -out device.key 2048
        openssl req -new -key device.key -subj "/CN=${DOMAIN}" -out device.csr
        openssl x509 -req -in device.csr -CA base.pem -CAkey base.key -CAcreateserial -days 10000 -out device.crt
    fi
    # cp -r base.pem /ngrok/assets/client/tls/ngrokroot.crt
}

## 初始化路径信息
echo "========> STL::Build[Init]"

buildPath=$(pwd)
time=$(date "+%Y%m%d%H%M%S")
prefixPath="${buildPath}/dist${time}"
certPath="${buildPath}/cert"
mkdir "${prefixPath}"
cd "${prefixPath}" || exit 1
prefixPath=$(pwd)
cd "${buildPath}" || exit 1
cp ./build.sh "${prefixPath}/build_back.sh"
libPath="/home/liuyuelong/workspace/ngrok.git"
cd "${libPath}" || exit 1
libPath=$(pwd)
git branch -v | grep -F "*" | tee version.log
mv version.log "${prefixPath}/"
domain="ngrok.liuyunuo.cn"

echo "buildPath:${buildPath}"
echo "prefixPath:${prefixPath}"
echo "libPath:${libPath}"
echo "certPath:${certPath}"
# 生成证书

gen_cert2 ${certPath} ${domain}

exit 0

